﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BEGDC.PreContract.BLL;
using BEGDC.Utility.Castle;

namespace PreContractWeb.Task
{
    public partial class FeedbackPreContract : System.Web.UI.Page
    {
        /// <summary>
        /// Feedback Pre-contract status
        /// </summary>
        protected bool isFeedback
        {
            get
            {
                if (Page.Request.QueryString["isFeedback"] == "false")
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        private BEGDC.PreContract.BLL.Authentication.PCIdentity user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);

            if (!Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Feedbacker.ToString()))
            {
                this.divError.InnerHtml = AlertMessage.NoFeedbackerPermission;
                this.divConnect.Visible = false;
                this.divError.Visible = true;
            }
            else if (!Page.IsPostBack)
            {
                this.BindDateGrid();
            }
        }

        private void BindDateGrid()
        {
            try
            {
                BEGDC.PreContract.BLL.ISalesFeedback iSalesFeedback = (BEGDC.PreContract.BLL.ISalesFeedback)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_SalesFeedback_Service];
                user = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);

                DataTable dt = new DataTable();
                if (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString()))
                {
                    if (isFeedback)
                    {
                        dt = iSalesFeedback.GetFeedbackPreContract(this.tbContractNo.Text.Trim(), this.tbContractName.Text.Trim(), this.tbProduct.Text.Trim(), user.EmployeeId, true);
                    }
                    else
                    {
                        dt = iSalesFeedback.GetNoFeedbackPreContract(this.tbContractNo.Text.Trim(), this.tbContractName.Text.Trim(), this.tbProduct.Text.Trim(), user.EmployeeId, true);
                    }
                }
                else
                {
                    if (isFeedback)
                    {
                        dt = iSalesFeedback.GetFeedbackPreContract(this.tbContractNo.Text.Trim(), this.tbContractName.Text.Trim(), this.tbProduct.Text.Trim(), user.EmployeeId, false);
                    }
                    else
                    {
                        dt = iSalesFeedback.GetNoFeedbackPreContract(this.tbContractNo.Text.Trim(), this.tbContractName.Text.Trim(), this.tbProduct.Text.Trim(), user.EmployeeId, false);
                    }
                }

                //Bind PreContract GridView 
                this.gvPreContractInfo.DataSource = dt.DefaultView;
                this.gvPreContractInfo.DataBind();
                this.pgPreContractInfo.Visible = true;
                this.pgPreContractInfo.BindtoGridView(this.gvPreContractInfo, dt.DefaultView);
                if (dt.Rows.Count == 0)
                {
                    this.pgPreContractInfo.Visible = false;
                }

                //Bind SalesFeedback GridView 
                this.gvSalesFeedBack.DataSource = dt.DefaultView;
                this.gvSalesFeedBack.DataBind();
                this.pgSalesFeedback.Visible = true;
                this.pgSalesFeedback.BindtoGridView(this.gvSalesFeedBack, dt.DefaultView);
                if (dt.Rows.Count == 0)
                {
                    this.pgSalesFeedback.Visible = false;
                }

                //Get Feedback Contract Count
                this.BindFeedbackCount(iSalesFeedback);
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        /// <summary>
        /// Get Feedback count
        /// </summary>
        /// <param name="iSalesFeedback">Sales Feedback Services</param>
        private void BindFeedbackCount(BEGDC.PreContract.BLL.ISalesFeedback iSalesFeedback)
        {
            this.lblFeedbackPreContractCount.Text = iSalesFeedback.GetFeedbackPreContractCount().ToString();
            this.lblNoFeedbackPreContractCount.Text = iSalesFeedback.GetNoFeedbackPreContractCount().ToString();
        }

        protected void gvPreContractInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                DataRowView row = (DataRowView)e.Row.DataItem;
                e.Row.Cells[1].Text = "<a onclick=\"javascript:ShowPage('" + row.Row["PreContractID"].ToString() + "');\">" + e.Row.Cells[1].Text.Trim() + "</a>";
                e.Row.Cells[2].Text = e.Row.Cells[2].Text.Length > 20 ? e.Row.Cells[2].Text.Substring(0, 20) + "..." : e.Row.Cells[2].Text;
            }
        }

        protected void gvSalesFeedBack_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0 && e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView row = (DataRowView)e.Row.DataItem;

                bool hasFirstText = true;
                DropDownList dpSignType = (DropDownList)e.Row.FindControl("dpSignType");
                DropDownList dpTreatmentWay = (DropDownList)e.Row.FindControl("dpTreatmentWay");
                DropDownList dpInvoiceStaus = (DropDownList)e.Row.FindControl("dpInvoiceStaus");
                DropDownList dpCancelProcess = (DropDownList)e.Row.FindControl("dpCancelProcess");
                DropDownList dpProblemLV1 = (DropDownList)e.Row.FindControl("dpProblemLV1");
                DropDownList dpProblemLV2 = (DropDownList)e.Row.FindControl("dpProblemLV2");
                DropDownList dpDashboardIssueType = (DropDownList)e.Row.FindControl("dpDashboardIssueType");
                Button btnSave = (Button)e.Row.FindControl("btnSave");

                BaseFunction.BindDicItemDropDownListByDicType(dpSignType, DicType.DictionaryType.SignType, string.Empty, hasFirstText);
                BaseFunction.BindDicItemDropDownListByDicType(dpTreatmentWay, DicType.DictionaryType.TreatmentWay, string.Empty, hasFirstText);
                BaseFunction.BindDicItemDropDownListByDicType(dpInvoiceStaus, DicType.DictionaryType.InvoiceStatus, string.Empty, hasFirstText);
                BaseFunction.BindDicItemDropDownListByDicType(dpCancelProcess, DicType.DictionaryType.CancelProcess, string.Empty, hasFirstText);
                BaseFunction.BindDicItemDropDownListByDicType(dpProblemLV1, DicType.DictionaryType.ProblemLV1, string.Empty, hasFirstText);
                BaseFunction.BindDicItemDropDownListByDicType(dpDashboardIssueType, DicType.DictionaryType.DashboardIssueType, string.Empty, hasFirstText);

                if (isFeedback)
                {
                    dpSignType.SelectedValue = row.Row["SignType"].ToString();
                    dpTreatmentWay.SelectedValue = row.Row["TreatmentWay"].ToString();
                    dpInvoiceStaus.SelectedValue = row.Row["InvoiceStatus"].ToString();
                    dpCancelProcess.SelectedValue = row.Row["CancelProcess"].ToString();
                    dpProblemLV1.SelectedValue = row.Row["ProblemLV1"].ToString();
                    dpDashboardIssueType.SelectedValue = row.Row["DashboardIssueType"].ToString();

                    if (!string.IsNullOrEmpty(dpProblemLV1.SelectedValue))
                    {
                        BaseFunction.BindDicItemDropDownListByDicType(dpProblemLV2, Convert.ToInt32(dpProblemLV1.SelectedValue));
                        dpProblemLV2.SelectedValue = row.Row["ProblemLV2"].ToString();
                    }

                    TextBox tbTreatmentDate = (TextBox)e.Row.FindControl("tbTreatmentDate");
                    tbTreatmentDate.Text = Convert.ToDateTime(row.Row["OperationDate"].ToString()).ToShortDateString();

                    TextBox tbPeopleInCharge = (TextBox)e.Row.FindControl("tbPeopleInCharge");
                    tbPeopleInCharge.Text = row.Row["PeopleInCharge"].ToString();

                    TextBox tbComments = (TextBox)e.Row.FindControl("tbComments");
                    tbComments.Text = row.Row["Comments"].ToString();
                }
            }
        }

        protected void gvSalesFeedBack_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Save" && !string.IsNullOrEmpty(e.CommandArgument.ToString()))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = this.gvSalesFeedBack.Rows[index];

                string precontractID = this.gvSalesFeedBack.DataKeys[index].Value.ToString();
                BEGDC.PreContract.DAL.PreContractInfo preContractInfo = new BEGDC.PreContract.DAL.PreContractInfo();
                preContractInfo.PreContractID = Convert.ToInt32(precontractID);

                DropDownList dpSignType = (DropDownList)row.FindControl("dpSignType");
                DropDownList dpTreatmentWay = (DropDownList)row.FindControl("dpTreatmentWay");
                DropDownList dpInvoiceStaus = (DropDownList)row.FindControl("dpInvoiceStaus");
                DropDownList dpCancelProcess = (DropDownList)row.FindControl("dpCancelProcess");
                DropDownList dpProblemLV1 = (DropDownList)row.FindControl("dpProblemLV1");
                DropDownList dpProblemLV2 = (DropDownList)row.FindControl("dpProblemLV2");
                DropDownList dpDashboardIssueType = (DropDownList)row.FindControl("dpDashboardIssueType");
                TextBox tbTreatmentDate = (TextBox)row.FindControl("tbTreatmentDate");
                TextBox tbPeopleInCharge = (TextBox)row.FindControl("tbPeopleInCharge");
                TextBox tbComments = (TextBox)row.FindControl("tbComments");

                if (this.CheckValues(dpSignType, dpTreatmentWay, dpInvoiceStaus, dpCancelProcess, dpProblemLV1, dpProblemLV2, dpDashboardIssueType, tbTreatmentDate, tbPeopleInCharge))
                {
                    BEGDC.PreContract.DAL.DicItem signTypeDicItem = this.GetDicItem(dpSignType);
                    BEGDC.PreContract.DAL.DicItem treatmentWayDicItem = this.GetDicItem(dpTreatmentWay);
                    BEGDC.PreContract.DAL.DicItem invoiveStatusDicItem = this.GetDicItem(dpInvoiceStaus);
                    BEGDC.PreContract.DAL.DicItem cancelProcessDicItem = this.GetDicItem(dpCancelProcess);
                    BEGDC.PreContract.DAL.DicItem problemLV1DicItem = this.GetDicItem(dpProblemLV1);
                    BEGDC.PreContract.DAL.DicItem problemLV2DicItem = this.GetDicItem(dpProblemLV2);
                    BEGDC.PreContract.DAL.DicItem dashboardIssueTypeDicItem = this.GetDicItem(dpDashboardIssueType);
                    Nullables.NullableDateTime operationDate = Convert.ToDateTime(tbTreatmentDate.Text);

                    user = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);
                    BEGDC.PreContract.BLL.IEmployee iEmployee = (BEGDC.PreContract.BLL.IEmployee)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Employee_Service];
                    BEGDC.PreContract.DAL.Employee creator = iEmployee.GetEmployee(user.EmployeeId);

                    BEGDC.PreContract.BLL.ISalesFeedback iSalesFeedback = (BEGDC.PreContract.BLL.ISalesFeedback)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_SalesFeedback_Service];
                    iSalesFeedback.AddSalesFeedback(
                        preContractInfo, signTypeDicItem, treatmentWayDicItem, operationDate, invoiveStatusDicItem,
                        cancelProcessDicItem, problemLV1DicItem, problemLV2DicItem,
                        tbComments.Text.Trim(), dashboardIssueTypeDicItem, tbPeopleInCharge.Text.Trim(), creator);

                    this.BindDateGrid();
                }
            }
        }

        protected void pgPreContractInfo_After_PageChanged(object sender, EventArgs e)
        {
            int index = this.pgPreContractInfo.GVCurrentPageIndex;
            this.pgSalesFeedback.GVCurrentPageIndex = index;
            this.pgSalesFeedback.PageChangeEvent();
            BindDateGrid();
        }

        private BEGDC.PreContract.DAL.DicItem GetDicItem(DropDownList drop)
        {
            string dicItemID = drop.SelectedValue;

            BEGDC.PreContract.DAL.DicItem dicItem = new BEGDC.PreContract.DAL.DicItem();
            dicItem.DicItemID = Convert.ToInt32(dicItemID); ;

            return dicItem;
        }

        protected void btnQuickSearch_Click(object sender, EventArgs e)
        {
            this.pgPreContractInfo.GVCurrentPageIndex = 1;
            this.pgSalesFeedback.GVCurrentPageIndex = 1;
            this.BindDateGrid();
        }

        protected void btnClearSearch_Click(object sender, EventArgs e)
        {
            this.tbContractNo.Text = string.Empty;
            this.tbContractName.Text = string.Empty;
            this.tbProduct.Text = string.Empty;

            this.pgPreContractInfo.GVCurrentPageIndex = 1;
            this.pgSalesFeedback.GVCurrentPageIndex = 1;
            this.BindDateGrid();
        }

        protected void DpProblemLV1_TextChanged(object sender, EventArgs e)
        {
            DropDownList dpProblemLV1 = (DropDownList)sender;

            if (!string.IsNullOrEmpty(dpProblemLV1.SelectedValue))
            {
                GridViewRow row = (GridViewRow)dpProblemLV1.NamingContainer;
                DropDownList dpProblemLV2 = (DropDownList)row.FindControl("dpProblemLV2");
                dpProblemLV2.Items.Clear();

                BaseFunction.BindDicItemDropDownListByDicType(dpProblemLV2, Convert.ToInt32(dpProblemLV1.SelectedValue));
            }
        }

        #region Check Values

        private bool CheckValues(DropDownList dpSignType, DropDownList dpTreatmentWay, DropDownList dpInvoiceStaus, DropDownList dpCancelProcess, DropDownList dpProblemLV1, DropDownList dpProblemLV2, DropDownList dpDashboardIssueType, TextBox tbTreatmentDate, TextBox tbPeopleInCharge)
        {
            DateTime dt;
            string result = string.Empty;

            if (string.IsNullOrEmpty(dpSignType.SelectedValue)) result += "请选择签约方式. \\r\\n";
            if (string.IsNullOrEmpty(dpTreatmentWay.SelectedValue)) result += "请选择处理方式. \\r\\n";

            if (string.IsNullOrEmpty(tbTreatmentDate.Text.Trim()))
            {
                result += "请输入处理日期. \\r\\n";
            }
            else if (!DateTime.TryParse(tbTreatmentDate.Text.Trim(), out dt))
            {
                result += "请输入的处理日期有误. \\r\\n";
            }
            else if (DateTime.Parse(tbTreatmentDate.Text.Trim()) < DateTime.Today.Date)
            {
                result += "您输入的处理日期不能小于当天日期. \\r\\n";
            }

            if (string.IsNullOrEmpty(dpInvoiceStaus.SelectedValue)) result += "请选择到货当季能否开票. \\r\\n";
            if (string.IsNullOrEmpty(dpCancelProcess.SelectedValue)) result += "请选择取消进展. \\r\\n";
            if (string.IsNullOrEmpty(dpProblemLV1.SelectedValue)) result += "请选择问题分类一级. \\r\\n";
            if (string.IsNullOrEmpty(dpProblemLV2.SelectedValue)) result += "请选择问题分类二级. \\r\\n";
            if (string.IsNullOrEmpty(dpDashboardIssueType.SelectedValue)) result += "请选择Dashboard Issue分类. \\r\\n";
            if (string.IsNullOrEmpty(tbPeopleInCharge.Text.Trim())) result += "请输入预合同当前负责人. \\r\\n";

            if (!string.IsNullOrEmpty(result))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + result + "')</script>");
                return false;
            }

            return true;
        }

        #endregion
    }
}